// pages/index/index.js
const { get } = require('../../utils/request')
const { getImageUrl, showError, checkLogin, debounce } = require('../../utils/util')

Page({
  data: {
    petList: [],
    searchName: '',
    typeIndex: 0,
    statusIndex: 0,
    typeList: ['全部类型', '猫', '狗', '其他'],
    statusList: ['全部状态', '待领养', '已领养'],
    loading: false,
    hasMore: true,
    pageNum: 1,
    pageSize: 10,
    // 公告相关数据
    noticeList: [],
    noticeLoading: false
  },

  onLoad() {
    this.loadNoticeList()
    this.loadPetList()
  },

  onShow() {
    // 每次显示页面时刷新数据
    this.setData({
      pageNum: 1,
      petList: []
    })
    this.loadNoticeList()
    this.loadPetList()
  },

  onPullDownRefresh() {
    this.setData({
      pageNum: 1,
      petList: []
    })
    this.loadNoticeList()
    this.loadPetList(() => {
      wx.stopPullDownRefresh()
    })
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.setData({
        pageNum: this.data.pageNum + 1
      })
      this.loadPetList()
    }
  },

  // 加载公告列表
  loadNoticeList() {
    if (this.data.noticeLoading) return

    this.setData({ noticeLoading: true })

    get('/notice/selectAll').then(res => {
      const noticeList = res.data || []

      // 只显示最新的一条公告
      const displayNotices = noticeList.length > 0 ? [noticeList[0]] : []

      // 格式化时间和内容
      displayNotices.forEach(item => {
        if (item.time) {
          // 如果时间是ISO格式，转换为友好格式
          const date = new Date(item.time)
          if (!isNaN(date.getTime())) {
            item.displayTime = this.formatTime(date)
          } else {
            item.displayTime = item.time
          }
        }

        // 截取内容显示
        if (item.content && item.content.length > 80) {
          item.shortContent = item.content.substring(0, 80) + '...'
        } else {
          item.shortContent = item.content || ''
        }
      })

      this.setData({
        noticeList: displayNotices
      })
    }).catch(err => {
      console.error('加载公告失败:', err)
    }).finally(() => {
      this.setData({ noticeLoading: false })
    })
  },

  // 格式化时间
  formatTime(date) {
    const now = new Date()
    const diff = now.getTime() - date.getTime()
    const days = Math.floor(diff / (1000 * 60 * 60 * 24))

    if (days === 0) {
      return '今天'
    } else if (days === 1) {
      return '昨天'
    } else if (days < 7) {
      return `${days}天前`
    } else {
      return `${date.getMonth() + 1}-${date.getDate()}`
    }
  },

  // 加载宠物列表
  loadPetList(callback) {
    if (this.data.loading) return

    this.setData({ loading: true })

    const params = {
      pageNum: this.data.pageNum,
      pageSize: this.data.pageSize
    }

    // 添加搜索条件
    if (this.data.searchName) {
      params.name = this.data.searchName
    }

    // 添加类型筛选
    if (this.data.typeIndex > 0) {
      params.type = this.data.typeList[this.data.typeIndex]
    }

    // 添加状态筛选
    if (this.data.statusIndex > 0) {
      params.status = this.data.statusList[this.data.statusIndex]
    }

    get('/pet/list', params).then(res => {
      const newList = res.data || []
      
      // 处理图片路径
      newList.forEach(item => {
        if (item.images) {
          const images = item.images.split(',')
          item.imageUrl = getImageUrl(images[0]) || '/images/default-pet.png'
        } else {
          item.imageUrl = '/images/default-pet.png'
        }
      })

      if (this.data.pageNum === 1) {
        this.setData({
          petList: newList,
          hasMore: newList.length >= this.data.pageSize
        })
      } else {
        this.setData({
          petList: [...this.data.petList, ...newList],
          hasMore: newList.length >= this.data.pageSize
        })
      }
    }).catch(err => {
      showError('加载失败')
    }).finally(() => {
      this.setData({ loading: false })
      callback && callback()
    })
  },

  // 搜索输入
  onSearchInput: debounce(function(e) {
    this.setData({
      searchName: e.detail.value,
      pageNum: 1,
      petList: []
    })
    this.loadPetList()
  }, 500),

  // 类型筛选
  onTypeChange(e) {
    this.setData({
      typeIndex: parseInt(e.detail.value),
      pageNum: 1,
      petList: []
    })
    this.loadPetList()
  },

  // 状态筛选
  onStatusChange(e) {
    this.setData({
      statusIndex: parseInt(e.detail.value),
      pageNum: 1,
      petList: []
    })
    this.loadPetList()
  },

  // 重置筛选
  onReset() {
    this.setData({
      searchName: '',
      typeIndex: 0,
      statusIndex: 0,
      pageNum: 1,
      petList: []
    })
    this.loadPetList()
  },

  // 跳转到详情页
  goToDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/pet-detail/pet-detail?id=${id}`
    })
  },

  // 申请领养
  onAdopt(e) {
    e.stopPropagation()

    // 检查登录状态，未登录跳转到游客提示页面
    const app = getApp()
    if (!app.globalData.isLogin) {
      wx.navigateTo({
        url: '/pages/guest-prompt/guest-prompt'
      })
      return
    }

    const { id, name } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/adoption/adoption?petId=${id}&petName=${name}`
    })
  },

  // 查看公告详情
  viewNoticeDetail(e) {
    const notice = e.currentTarget.dataset.notice
    wx.showModal({
      title: notice.title,
      content: notice.content,
      showCancel: false,
      confirmText: '知道了'
    })
  },

  // 查看更多公告
  viewMoreNotices() {
    // 检查是否为管理员，如果是则跳转到管理页面，否则显示所有公告
    const app = getApp()
    if (app.globalData.userInfo && app.globalData.userInfo.role === 'ADMIN') {
      wx.navigateTo({
        url: '/pages/admin/notice-manage/notice-manage'
      })
    } else {
      // 显示所有公告的弹窗或跳转到公告列表页面
      this.showAllNotices()
    }
  },

  // 显示所有公告
  showAllNotices() {
    get('/notice/selectAll').then(res => {
      const noticeList = res.data || []
      if (noticeList.length === 0) {
        wx.showToast({
          title: '暂无公告',
          icon: 'none'
        })
        return
      }

      // 构建公告内容字符串
      let content = ''
      noticeList.forEach((notice, index) => {
        content += `${index + 1}. ${notice.title}\n${notice.content}\n\n`
      })

      wx.showModal({
        title: '系统公告',
        content: content.trim(),
        showCancel: false,
        confirmText: '知道了'
      })
    }).catch(err => {
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    })
  }
})
